﻿using LiteDB;

namespace CommandLib.Helper
{
    /// <summary>
    /// Litedb操作类
    /// </summary>

    public class LitedbHelper : IDisposable
    {
        /// <summary>
        /// 数据库对象
        /// </summary>
        private LiteDatabase instance;
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="dbname">数据库路径： test.db</param>
        /// <exception cref="Exception"></exception>
        public LitedbHelper(string dbname)
        {
            instance = new LiteDatabase(dbname);
            if (instance == null)
            {
                throw new Exception("数据库创建失败！");
            }
        }

        /// <summary>
        /// 判断数据表是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>         

        public bool HasTable(string name)
        {
            return instance.GetCollectionNames().Contains(name);
        }

        /// <summary>
        /// 获取数据库
        /// </summary>

        public LiteDatabase DataBase { get { return instance; } }
        /// <summary>
        /// 创建表格
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="table">表名</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>

        public ILiteCollection<T> CreatTable<T>(string table) where T : class, new()
        {
            return instance.GetCollection<T>(table);
        }
        /// <summary>
        /// 获取表格操作
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="tbname">表名</param>
        /// <returns></returns>

        public ILiteCollection<T> GetTable<T>(string tbname) where T : class, new()
        {
            return instance.GetCollection<T>(tbname);
        }

        /// <summary>
        /// 删除表格
        /// </summary>
        /// <param name="table"></param>

        public void ReMoveTable(string table)
        {
            instance?.DropCollection(table);
        }
        public void Dispose()
        {
            instance?.Dispose();
        }
    }
}
